var fileKey = "fileList";
var baseUrl = "http://127.0.0.1:8080";

function addList(fileUrl) {
  var fileList = JSON.parse(localStorage.getItem(fileKey));
  if (!fileList) {
    fileList = [];
  }
  fileList.push(fileUrl);
  $("#file-list").append(
    `<li class="list-group-item" ><a href="${fileUrl}" target="_blank">${fileUrl}</a></li>`
  );
  window.localStorage.setItem(fileKey, JSON.stringify(fileList));
}

function fillList() {
  var fileList = JSON.parse(localStorage.getItem(fileKey));
  if (fileList && fileList.length) {
    for (var fileUrl of fileList) {
      $("#file-list").append(
        `<li class="list-group-item" ><a href="${fileUrl}" target="_blank">${fileUrl}</a></li>`
      );
    }
  }
}

async function uploadFile(file) {
  var fileSize = file.size;
  var chunkSize = 5 * 1024 * 1024; // 分块大小
  if (fileSize <= chunkSize) {
    // 普通上传
    var formData = new FormData();
    formData.append("file", file);
    $.ajax({
      url: baseUrl + "/api/upload/file",
      type: "put",
      contentType: false,
      processData: false,
      data: formData,
      success: function (res) {
        if (res.code == 200) {
          Toast.fire({
            icon: "success",
            title: "文件上传成功",
          });
          addList(res.data);
        } else {
          Toast.fire({
            icon: "error",
            title: res.msg,
          });
        }
      },
    });
  } else {
    // 分片上传
    var blobSlice =
      File.prototype.slice ||
      File.prototype.mozSlice ||
      File.prototype.webkitSlice;
    var chunks = Math.ceil(file.size / chunkSize);
    var checkParam = {
      fileName: file.name,
      chunks: chunks,
      contentType: file.type,
    };
    $.ajax({
      type: "POST",
      url: baseUrl + "/api/upload/multipart/create",
      cache: false,
      data: JSON.stringify(checkParam),
      contentType: "application/json",
      success: async function (res) {
        if (res.code == 200) {
          var result = res.data;
          var total = result.chunks;
          var uploadId = result.uploadId;
          var objectName = result.fileName;
          for (var i = 1; i <= total; i++) {
            var start = (i - 1) * chunkSize;
            var end = Math.min(fileSize, start + chunkSize);
            var _chunkFile = blobSlice.call(file, start, end);
            var fragmentData = new FormData();
            fragmentData.append("fileName", objectName);
            fragmentData.append("uploadId", uploadId);
            fragmentData.append("partNumber", i);
            fragmentData.append("file", _chunkFile);
            await $.ajax({
              url: baseUrl + "/api/upload/multipart/upload",
              type: "PUT",
              contentType: false,
              processData: false,
              data: fragmentData,
              success: function () {
                console.log("第" + i + "个分片上传完成");
              },
            });
          }
          var completeParams = JSON.stringify({
            uploadId: uploadId,
            fileName: objectName,
            chunks: total,
            fileSize: fileSize,
            contentType: file.type,
          });
          $.ajax({
            url: baseUrl + "/api/upload/multipart/complete",
            type: "POST",
            contentType: "application/json",
            processData: false,
            data: completeParams,
            success: function (res) {
              if (res.code == 200) {
                Toast.fire({
                  icon: "success",
                  title: "文件上传成功",
                });
                addList(res.data.url);
              } else {
                Toast.fire({
                  icon: "error",
                  title: res.msg,
                });
              }
            },
          });
        } else {
          Toast.fire({
            icon: "error",
            title: res.msg,
          });
        }
      },
      error: function () {
        Toast.fire({
          icon: "error",
          title: "文件上传失败",
        });
      },
    });
  }
}

$(function () {
  $("button#uploadBtn").on("click", function () {
    $("input#file").click();
  });

  $("input#file").on("change", function () {
    var files = $(this).prop("files");
    if (files && files.length) {
      var file = files[0];
      uploadFile(file);
    }
  });

  fillList();
});
